<template>
  <div class="taskHandle">
    <basic-container>
      <el-form ref="add-form" :model="form" :rules="rules">
        <h3>预算调整申请信息</h3>
        <el-divider></el-divider>
        <table class="customTable" align="center">
          <tr style="text-align: center">
            <th width="350">预算编号：</th>
            <th width="400">{{this.form.applyData.budgetCode}}</th>
            <th width="350">申请名称：</th>
            <th width="400">{{this.form.applyData.applyName}}</th>
          </tr>

          <tr style="text-align: center">
            <th width="350">申请部门：</th>
            <th width="400">{{applyDept2}}</th>
            <th width="350">申请类型：</th>
            <th width="400">{{applyType2}}</th>
          </tr>

          <!--                <tr style="text-align: center">-->
          <!--                    <th colspan="4">-->
          <!--                        <el-form-item label="原预算额(元)"-->
          <!--                                      prop="applyData.budgetSum">-->
          <!--                            <el-input v-model="form.applyData.budgetSum"  readonly="readonly" placeholder="原预算额(元)"/>-->
          <!--                        </el-form-item>-->
          <!--                    </th>-->
          <!--                </tr>-->

          <!--                <tr style="text-align: center">-->
          <!--                    <th colspan="4">-->
          <!--                        <el-form-item label="调整后预算额(元)"-->
          <!--                                      prop="applyData.budgetSum2">-->
          <!--                            <el-input v-model="form.applyData.budgetSum2"  readonly="readonly" placeholder="调整后预算额(元)"/>-->
          <!--                        </el-form-item>-->
          <!--                    </th>-->
          <!--                </tr>-->

          <!--                <tr style="text-align: center">-->
          <!--                    <th colspan="4">-->
          <!--                        <el-form-item label="预算变化(元)"-->
          <!--                                      prop="applyData.changeAmount">-->
          <!--                            <el-input v-model="form.applyData.changeAmount" readonly="readonly"  placeholder="预算变化(元)"/>-->
          <!--                        </el-form-item>-->
          <!--                    </th>-->
          <!--                </tr>-->
          <!--                <tr style="text-align: center">-->
          <!--                    <th colspan="4">-->
          <!--                        <el-form-item label="备注" prop="applyData.remarks">-->
          <!--                            <el-input v-model="form.applyData.remarks"  placeholder="请输入备注" readonly="readonly"/>-->
          <!--                        </el-form-item>-->
          <!--                    </th>-->
          <!--                </tr>-->

          <tr>
            <td class="label">费用说明：</td>
            <td colspan="3">{{this.form.applyData.remarks}}</td>
          </tr>
        </table>

        <el-table
          :data="form.itemValueList"
          class="flowTable mt20"
          row-key="itemId"
          default-expand-all
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        >
          <el-table-column class="weight" header-align="center" prop="itemName" label="科目" width="300">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.itemName }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="原金额(元)">
            <el-table-column align="center" prop="itemValue" :label="`${form.applyData.budgetSum}`" />
          </el-table-column>
          <el-table-column align="center" label="调整后金额(元)">
            <!-- <el-table-column  align="center" prop="itemValuePre" :label="`${form.applyData.budgetSum2}`"/> -->
            <el-table-column align="center" prop="itemValuePre" :label="`${form.applyData.budgetSum2 || '暂无数据'}`">
              <template slot-scope="scope">
                <el-input clearable maxlength="15" @input="budgetChange" :readonly="scope.row.children !== null" v-model="scope.row.itemValuePre" />
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column align="center" label="变化金额(元)">
            <el-table-column align="center" prop="itemValue" :label="`${form.applyData.changeAmount || '暂无数据'}`">
              <template slot-scope="scope">{{`${scope.row.changeAmount>0 ? '+':''}${scope.row.changeAmount || 0}`}}</template>
            </el-table-column>
          </el-table-column>
        </el-table>

        <!--            <h3>预算科目</h3>-->
        <!--            <el-divider></el-divider>-->
        <!--            <el-table :data="this.form.itemValueList" class="flowTable"  stripe>-->

        <!--                <el-table-column label="科目名称" prop="itemName">-->
        <!--                    <template slot-scope="scope">-->
        <!--                        <el-input v-model="scope.row.itemName" readonly="readonly"></el-input>-->
        <!--                    </template>-->
        <!--                </el-table-column>-->

        <!--                <el-table-column label="原金额(元)" prop="itemValue">-->
        <!--                    <template slot-scope="scope">-->
        <!--                        <el-input v-model="scope.row.itemValue" readonly="readonly"></el-input>-->
        <!--                    </template>-->
        <!--                </el-table-column>-->

        <!--                <el-table-column label="调整后金额(元)" prop="itemValuePre">-->
        <!--                    <template slot-scope="scope">-->
        <!--                        <el-input v-model="scope.row.itemValuePre" readonly="readonly"></el-input>-->
        <!--                    </template>-->
        <!--                </el-table-column>-->

        <!--                <el-table-column label="变化金额(元)" prop="changeAmount">-->
        <!--                    <template slot-scope="scope">-->
        <!--                        <el-input v-model="scope.row.changeAmount" readonly="readonly"></el-input>-->
        <!--                    </template>-->
        <!--                </el-table-column>-->
        <!--            </el-table>-->
      </el-form>

      <!--            <h3>文件上传</h3>-->
      <!--            <el-divider></el-divider>-->
      <!--            <div>-->
      <!--                <upload-media type="file"-->
      <!--                              ref="myApply"-->
      <!--                              :busId="busId"-->
      <!--                              :modelType="modelType"-->
      <!--                              :isShowFileList="true"-->
      <!--                              :isView="true">-->
      <!--                </upload-media>-->
      <!--                <upload-media type="file"-->
      <!--                              ref="myApply2"-->
      <!--                              :busId="busId2"-->
      <!--                              :modelType="modelType"-->
      <!--                              :isShowFileList="true"-->
      <!--                              :isView="true">-->
      <!--                </upload-media>-->
      <!--            </div>-->

      <fileUpload type="preview" :busId="fileId" :fileId="fileId2" v-if="showUpload" />

      <fileUpload type="preview" :busId="fileId3" :fileId="fileId4" firstTitle="预算申请附件材料" secondTitle="预算申请业务依据" v-if="showUpload" />

      <h3>流程记录</h3>
      <el-divider></el-divider>
      <el-table :data="busifoData" class="flowTable" stripe>
        <el-table-column label="序号" type="index" width="75" align="center" />
        <el-table-column label="业务类型" prop="busiType" align="center" />
        <el-table-column label="办理环节" prop="taskName" align="center" />
        <el-table-column label="办理结果" prop="operResult" align="center">
          <template slot-scope="scope">
            <span v-for="(item,index) in operlts" :key="index" v-if="scope.row.operResult==item.id">{{item.value}}</span>
          </template>
        </el-table-column>
        <el-table-column label="办理意见" prop="operIdea" align="center" />
        <el-table-column label="经办人" prop="operPerson" align="center" />
        <el-table-column label="经办时间" prop="operaTime" align="center" />
      </el-table>

      <h3>业务办理</h3>
      <el-divider />
      <table class="customTable" :table-loading="tableLoading">
        <tr>
          <th class="label" align="right">
            <font>*</font>办理结果：
          </th>
          <td colspan="5">
            <el-radio-group v-model="radios" @change="onBljg()">
              <el-radio v-for="(iteam,index) in operResults" :key="index" :label="index">{{iteam.resultName}}</el-radio>
            </el-radio-group>
          </td>
        </tr>
        <tr>
          <td class="label" align="right">
            <font>*</font>办理意见：
          </td>
          <td colspan="5">
            <el-input type="textarea" placeholder="请输入内容" v-model="texts"></el-input>
          </td>
          <!--  <th><el-button type="primary" @click="Opinions()">常用意见</el-button></th>-->
        </tr>
        <tr>
          <td class="label" align="right">
            <font>*</font>办理时间：
          </td>
          <td>
            <el-input readonly v-model="datatime" />
          </td>
          <td class="label" align="center">
            <font>*</font>办理人：
          </td>
          <td>{{user.realName}}</td>
          <td class="label" align="center">
            <font>*</font>下一环节经办人：
          </td>
          <td>
            <el-input readonly v-model="nextResultName" />
          </td>
        </tr>
      </table>
      <div class="operaList">
        <el-button type="warning" :disabled="this.status == 0" @click="release()">释放任务</el-button>
        <el-button type="success" :disabled="this.status == 0" @click="uploadDeployInfo()">查看流程图</el-button>
        <el-button type="primary" :disabled="this.status == 0" v-throttle="[save]">提交</el-button>
        <el-button @click="returns()">返回</el-button>
      </div>
      <flow-chart ref="flowChart"></flow-chart>
      <history-routes ref="historyRoutes" style="display: none"></history-routes>
      <!--<busimain-opinions ref="busimainOpinions"></busimain-opinions>-->
    </basic-container>
  </div>
</template>

<script>
// import busimainOpinions from './busimain-opinions'
import axios from 'axios'
import flowChart from './flow-chart'
import dbl from '@/utils/dbl'
import historyRoutes from '@/layout/history-routes'
import { getDict } from "~/utils";
import uploadMedia from '@/components/upload-media'
import { getBudgetApply, getItem, getItem2, putObj, updateParameter } from "@/views/wy-budget/api/budgetapply.js";
import { getFiles, checkFiles, delFiles } from "@/views/wy-budget/api/fileoperation.js";
import { saveBudgetFlow } from "@/views/wy-budget/api/budgetflow.js";
import BaseLoad from '@/assets/vue-mixin/BaseLoad'
import { mapState } from 'vuex'
import fileUpload from '@/views/wy-budget/components/fileUpload'

export default {
  name: "business-handle",
  mixins: [BaseLoad],
  components: { flowChart, historyRoutes, uploadMedia, fileUpload },
  data () {
    var doubleValidate = (rule, value, callback) => {
      let reg = /^[0-9]+(.[0-9]{1,2})?$/;
      let lable = rule.message;
      if (!reg.test(value)) {
        return callback(new Error("数值格式错误"));
      } else {
        callback();
      }
    };

    return {
      showUpload: false,
      fileId: '',
      fileId2: '',
      fileId3: '',
      fileId4: '',
      radios: 0,  // 办理结果选择
      texts: '',
      tableLoading: false,
      datatime: formatTimeToStr(new Date().getTime()),  // 当前时间
      busiIds: [],
      busifoData: [],  //流转记录
      operResults: [], // 办理结果
      operlts: [{  //  流转记录
        id: "0",
        value: "不通过"
      }, {
        id: "1",
        value: "通过"
      }, {
        id: "9",
        value: "返回受理"
      }],
      nextResultName: '', // 下一个经办人
      UserId: '',
      status: 1,

      isShow: false,
      fileList: [],
      modelType: "budgetApply",
      busId: "",
      busId2: '',
      budgetFlow: {
        applyId: "",
        busiId: "",
        procInstId: "",
        applyDept: "",
      },

      form: {
        applyData: {
          applyId: "",
          busiId: "",
          budgetId: "",
          budgetCode: "",
          applyName: "",
          applyDept: "",
          applyType: "",
          budgetSum: "",
          remarks: "",
          fileId: ""
        },
        itemValueList: [],
        operateType: ""
      },

      rules: {

      }
    };
  },

  computed: {
    ...mapState({ user: state => state.user.user }),

    applyDept2: function () {
      let types = getDict('budget_department')
      let pv = this.form.applyData.applyDept
      if (pv && types.length > 0) {
        const pts = types.filter(t => t.value == pv)
        return pts ? pts[0].label : ''
      }
      return ''
    },

    applyType2: function () {
      let types = getDict('budget_type')
      let pv = this.form.applyData.applyType
      if (pv && types.length > 0) {
        const pts = types.filter(t => t.value == pv)
        return pts ? pts[0].label : ''
      }
      return ''
    }
  },

  mounted () {
    this.init();
  }
  ,
  methods: {
    init () {
      this.busiIds = this.$route.query.busiIds
      this.getList(this.busiIds.busiId)
    },

    uploadDeployInfo () {
      this.$refs.flowChart.show(this.busiIds)
    },
    save () {
      const loading = this.$loading({
        lock: true,
        text: '数据处理中'
      });
      const config = {
        headers: { 'Authorization': dbl.get('token'), }
      }
      axios.post("/api/flowbusimain/doSubmit", {
        busiId: this.busiIds.busiId,
        busiTaskCode: this.busiIds.busiTaskCode,
        operIdea: this.texts,
        operResult: this.operResults[this.radios].resultCode,
        userId: this.UserId
      }, config).then(response => {
        if (response.data.msg == "提交成功。") {
          this.$message.success(response.data.msg)

          if (this.operResults[this.radios].resultCode == '1') {
            // 通过
            console.log("通过")

            // 更新状态，生成台账
            getBudgetApply(this.busiIds.busiId).then(respData => {

              this.budgetApply = respData.data.data
              this.budgetApply.checkStatus = '102'

              putObj(this.budgetApply).then(respData => {

              }).catch(e => {

              })

              updateParameter(this.budgetApply).then(respData => {

              }).catch(e => {

              })

              this.budgetFlow.applyId = this.budgetApply.applyId
              this.budgetFlow.busiId = this.busiIds.busiId
              this.budgetFlow.procInstId = this.busiIds.procInstId
              this.budgetFlow.applyDept = this.budgetApply.applyDept


              saveBudgetFlow(this.budgetFlow).then(respData => {
              }).catch(e => {
              })

            }).catch(e => {

            })

          } else {
            // 不通过
            console.log("不通过")
            // 更新状态
            getBudgetApply(this.busiIds.busiId).then(respData => {

              this.budgetApply = respData.data.data
              this.budgetApply.checkStatus = '103';
              this.budgetApply.isEdit = '1'

              putObj(this.budgetApply).then(respData => {

              }).catch(e => {

              })

              this.budgetFlow.applyId = this.budgetApply.applyId
              this.budgetFlow.busiId = this.busiIds.busiId
              this.budgetFlow.procInstId = this.busiIds.procInstId
              this.budgetFlow.applyDept = this.budgetApply.applyDept


              saveBudgetFlow(this.budgetFlow).then(respData => {
              }).catch(e => {
              })

            }).catch(e => {

            })
          }

          // 获取办理 流程
          axios.get("/api/flowbusimain/getOperProcList/" + this.busiIds.busiId, config).then(response => {
            this.busifoData = response.data.data
          }).catch(e => {
          })
          loading.close()
          this.status = 0
        } else {
          this.$message.error(response.data.msg)
          loading.close()
        }
        this.release(1)
      }).catch(e => {
        loading.close()
      })

    },
    release (data) {  // 释放任务
      const config = {
        headers: { 'Authorization': dbl.get('token'), }
      }
      axios.get("/api/flowbusimain/doTaskUnLock/" + this.busiIds.busiId, config).then(response => {
        if (data == null) {
          if (response.data.msg == "释放任务成功。") {
            this.$message.success(response.data.msg)
            this.status = 0
            // this.returns()
          } else {
            this.$message.error(response.data.msg)
          }
        }
      }).catch(e => {
      })
    },
    onBljg (data) {  // 办理结果 变化事件
      this.texts = this.operResults[this.radios].resultName
      this.nextUser(this.operResults[this.radios].taskResultId)
    },
    nextUser (taskResultId) { // 下一步 办理人
      const config = {
        headers: { 'Authorization': dbl.get('token'), }
      }
      var thta = this
      axios.get("/api/flowbusimain/getTaskResultUserId/" + taskResultId, config).then(response => {
        let k = response.data.data;
        for (var i = 0; i < k.length; i++) {
          if (i == 0) {
            this.UserId = k[i].assigneeId + "SPLIT" + k[i].assignee
          } else {
            this.UserId += k[i].assigneeId + "SPLIT" + k[i].assignee
          }
          this.nextResultName = k[i].assignee
        }
        if (k.length == 0) {
          this.nextResultName = "无"
          this.UserId = ""
        }
      }).catch(e => {
      })
    },
    Opinions () {  // 常用意见
      this.$refs.busimainOpinions.show()
    },
    returns () { // 返回
      //this.$refs.historyRoutes.closeTab('current');
      this.$router.push({
        path: "daiban-list",
      })
      // this.$refs.historyRoutes.delTab('/wy-flow/daiban-list2')
    },
    getList (data) {
      var thta = this
      const config = {  // 获取请假信息
        headers: { 'Authorization': dbl.get('token'), }
      }

      // 预算申请业务逻辑
      getBudgetApply(data).then(respData => {
        if (respData.data.data == null) {
          this.returns()
        }
        this.form.applyData = respData.data.data

        this.initItem(this.form.applyData.applyId);

        this.fileId = this.form.applyData.fileId
        this.fileId2 = this.form.applyData.fileId2
        this.fileId3 = this.form.applyData.applyFileId
        this.fileId4 = this.form.applyData.applyFileId2
        this.showUpload = true;

        //
        // this.busId = respData.data.data.fileId;
        // this.$refs.myApply.getFiles(this.busId);
        //
        // this.busId2 = respData.data.data.applyFileId;
        // this.$refs.myApply2.getFiles(this.busId2);
      }).catch(e => {
      })

      // 获取办理 流程
      axios.get("/api/flowbusimain/getOperProcList/" + data, config).then(response => {
        this.busifoData = response.data.data
      }).catch(e => {
      })

      // 获取办理 结果
      axios.get("/api/flowbusimain/getTaskResultByTaskCode/" + data, config).then(response => {
        this.operResults = response.data.data
        this.texts = this.operResults[this.radios].resultName
        this.nextUser(this.operResults[this.radios].taskResultId)
      }).catch(e => {
      })
    },

    // 科目
    initItem () {
      getItem(this.form.applyData.applyId).then(rep => {
        let rspD = rep.data.data
        if (rspD) {
          rspD = rspD.map((rs, index) => {
            rs['sortNum'] = index + 1
            return rs
          })
        }
        this.form.itemValueList = rspD
      })
    },

    // 科目
    initItem2 () {
      getItem2(this.form.applyData.applyId).then(rep => {
        let rspD = rep.data.data
        if (rspD) {
          rspD = rspD.map((rs, index) => {
            rs['sortNum'] = index + 1
            return rs
          })
        }
        this.form.itemValueList = rspD
      })
    },

    // 下载
    handleClean (file) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          delFiles(file.fileId, this.modelType).then(resp => {
            if (resp.data.code === 0) {
              this.$message({
                type: "success",
                message: "删除成功!"
              });

              this.fileList = this.fileList.filter(
                file => file.fileId != fileId
              );
            } else {
              this.$message({
                type: "error",
                message: "删除失败!"
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
  }
}

Date.prototype.Format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1,                 //月份
    "d+": this.getDate(),                    //日
    "h+": this.getHours(),                   //小时
    "m+": this.getMinutes(),                 //分
    "s+": this.getSeconds(),                 //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds()             //毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}
export function formatTimeToStr (times) {
  var d = new Date(times).Format("yyyy-MM-dd hh:mm:ss");
  return d.toLocaleString();
}
</script>

<style lang="scss" scoped>
.taskHandle {
  h3 {
    padding-top: 15px;
    margin-top: 20px;
    &:first-child {
      margin-top: 0;
    }
  }
  /deep/ .el-divider {
    margin-top: 14px;
  }
  .operaList {
    margin-top: 30px;
    text-align: center;
    padding-bottom: 20px;
  }
}

.card-box {
  .card-title {
    margin-bottom: 20px;
  }
}

//表头结算样式
.header {
  height: 74px;
  text-align: center;
  margin: 0 auto;
  width: 99%;
  /* max-width: 99%; */

  .subject {
    font-size: 14px;
    width: 25%;
    height: 74px;
    line-height: 74px;
    text-align: left;
    border: 1px solid #ebeef5;
    font-weight: normal;
    padding-left: 20px;
    float: left;
  }

  .aggregate {
    height: 74px;
    float: right;
    width: 75%;

    .aggregatebox {
      height: 50%;
      width: 100%;

      .etui {
        font-size: 14px;
        border: 1px solid #ebeef5;
        width: 33.33%;
        height: 100%;
        line-height: 36px;
        text-align: center;
        font-weight: normal;
        float: left;
      }

      .etui /deep/ .el-form-item__content {
        margin-left: 0 !important;
      }

      // background-color: yellow;
    }
  }
}

// 树形结构修改默认样式
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  font-weight: normal;
  justify-content: space-between;
  /* font-size: 14px; */
  font-size: 14px;
  padding-right: 8px;
}

.box /deep/.el-tree-node__content {
  height: 53px;
}

// 修改开关组件
.box /deep/.el-switch__core {
  height: 14px;
}

//修改开关组件原型开关
.box /deep/.el-switch__core::after {
  height: 12px;
  width: 12px;
  margin-left: 0px;
  top: 0;
}

// 修改开关组件切换后样式
.box /deep/ .el-switch.is-checked .el-switch__core::after {
  margin-left: -14px;
  top: 0;
}

//
.inputbox {
  text-align: center;
}

//修改树形组件 输入框样式
.inputbox /deep/ .el-input__inner {
  height: 25px;
  width: 50%;
}

.footer /deep/.el-button {
  float: right;
  margin-right: 5px;
}
</style>
